import test from 'ava';
import sleep from '@3-/sleep';

const QUICKWIT_URL = 'http://localhost:7280';
const INDEX_ID = 'rag';
const DOC_ID = 11111111111;
const TIMESTAMP = Math.floor(Date.now() / 1000);

const request = async (path, body, method = 'POST') => {
  const url = `${QUICKWIT_URL}${path}`;
  const response = await fetch(url, {
    method: method,
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });

  if (!response.ok) {
    throw new Error(`Request to ${url} failed with status ${response.status}: ${await response.text()}`);
  }
  return response.json();
};

const createIndex = async () => {
  const conf = {
    version: "0.7",
    index_id: INDEX_ID,
    index_uri: "file:///data/rag",
    doc_mapping: {
      timestamp_field: "ts",
      field_mappings: [
        { name: "title", type: "text", tokenizer: "chinese_compatible", fieldnorms: true },
        { name: "content", type: "text", tokenizer: "chinese_compatible", fieldnorms: true },
        { name: "brief", type: "text", tokenizer: "chinese_compatible", fieldnorms: true },
        { name: "slogan", type: "text", tokenizer: "chinese_compatible", fieldnorms: true },
        { name: "id", type: "u64" },
        { name: "org_id", type: "u64", fast: true },
        { name: "user_id", type: "u64", fast: true },
        { name: "repo_id", type: "u64", fast: true },
        { name: "ts", type: "datetime", input_formats: ["unix_timestamp"], fast: true, fast_precision: "seconds" },
      ],
    },
    search_settings: {
      default_search_fields: ["title", "content", "brief", "slogan"],
    },
  };
  await request(`/api/v1/indexes?overwrite=true`, conf);
};

const recordDocument = async () => {
  console.log(`--- 步骤 1: 正在摄取文档 (ID: ${DOC_ID}) ---`);
  const document = {
    title: "Node.js 测试标题",
    content: `包含 ID ${DOC_ID} 的文档内容`,
    brief: "测试简介",
    slogan: "测试标语",
    id: DOC_ID,
    org_id: 101,
    user_id: 202,
    repo_id: 303,
    ts: TIMESTAMP,
    rm: false,
  };
  await request(`/api/v1/${INDEX_ID}/ingest?commit=force`, document);
};

const queryDocument = async () => {
  const response = await request(`/api/v1/${INDEX_ID}/search`, {
    query: `id:${DOC_ID} AND rm:false`,
    start_offset: 0,
    max_hits: 1,
  });

  console.log('搜索 API 响应:');
  console.log(JSON.stringify(response, null, 2));
  return response.hits.length > 0;
};

const markDocumentAsDeleted = async () => {
  console.log(`--- 步骤 3: 正在标记文档为已删除 (ID: ${DOC_ID}) ---`);
  const document = {
    id: DOC_ID,
    rm: true,
  };
  await request(`/api/v1/${INDEX_ID}/ingest?commit=force`, document);
};

const deleteIndex = async () => {
  console.log(`--- 步骤 5: 删除索引 (${INDEX_ID}) ---`);
  await request(`/api/v1/indexes/${INDEX_ID}`, {}, 'DELETE');
};

const waitForCondition = async (conditionFn, timeout, interval) => {
  const start = Date.now();
  while (Date.now() - start < timeout) {
    if (await conditionFn()) {
      return true;
    }
    await sleep(interval);
  }
  return false;
};

test.serial('Quickwit API 集成测试', async t => {
  await t.notThrowsAsync(createIndex(), '应该成功创建索引');
  console.log('索引创建成功。');

  await t.notThrowsAsync(recordDocument(), '应该成功录入文档');
  console.log('文档录入成功。');

  t.true(await queryDocument(), '应该找到已录入的文档');
  console.log('文档已找到。');

  await t.notThrowsAsync(markDocumentAsDeleted(), '应该成功标记文档为已删除');
  console.log('文档已成功标记为已删除。');

  // Give Quickwit some time to update the index
  await sleep(1000);

  t.false(await queryDocument(), '不应该找到已标记为删除的文档');

  await t.notThrowsAsync(deleteIndex(), '应该成功删除索引');
  console.log(`--- 步骤 5: 删除索引 (${INDEX_ID}) ---`);

  console.log('所有 Quickwit API 集成测试完成。');
});
